<template>
  <nut-config-provider :theme="theme" :theme-vars="themeVars">
    <view :style="{backgroundColor: 'white',padding: themeVars.pagePadding,height: '100vh'}">
      <nut-form
          ref="formRef"
          :model-value="formData"
          :rules="formRules"
      >
        <nut-form-item label="发布类型" prop="publishType">
          <nut-radio-group v-model="formData.publishType" direction="horizontal">
            <nut-radio :label="item.dictValue" :key="item.dictValue" v-for="item in dictList">{{ item.dictLabel }}
            </nut-radio>
          </nut-radio-group>
        </nut-form-item>

        <nut-form-item label="商品名称" prop="name">
          <nut-input
              v-model="formData.name"
              placeholder="请输入商品名称"
              type="text"

          />
        </nut-form-item>

        <nut-form-item label="联系人员" prop="contactName">
          <nut-input
              v-model="formData.contactName"
              placeholder="请输入联系人员"
              type="text"

          />
        </nut-form-item>

        <nut-form-item
            label="联系电话"
            prop="contactPhone"
        >
          <nut-input v-model="formData.contactPhone" placeholder="请输入联系电话" type="text"/>
        </nut-form-item>


        <nut-form-item label="联系地址" prop="contactAddr">
          <nut-input v-model="formData.contactAddr" placeholder="请选择地址" type="text" @click="selectLocation">
            <template #right>
              <IconFont

                  size="18"
                  name="location2"
                  color="red"
              ></IconFont>
            </template>
          </nut-input>
        </nut-form-item>

        <nut-form-item
            label="详情说明"
            prop="detail"
        >
          <nut-textarea v-model="formData.detailDesc" placeholder="请输入详情说明" type="text"/>
        </nut-form-item>
        <nut-form-item label="图片说明"
        >
          <nut-uploader
              v-model:file-list="formData.imgDesc"
              :url="`${baseUrl}${returnUrl}`"
              accept="image/*"
              maximum="9"
              multiple
              :headers="{token:token}"
              @success="({data,fileItem, option,responseText})=>{
              const resData = JSON.parse(data.data)
              fileItem.url = resData.data
                console.log('success',data,fileItem)
              }"
              @failure="({data,fileItem, option,responseText})=>{
                  const resData = JSON.parse(data.data)
                  Taro.showToast({ title: resData.msg, icon: 'error',   duration: 1500,  });
              }"
          >
          </nut-uploader>
        </nut-form-item>

        <view style="display: flex;justify-content: center;margin: 20px 0">
          <nut-button color="#0073ff" style="width: 200px" @click="submit"> 保存</nut-button>
        </view>
      </nut-form>
    </view>

  </nut-config-provider>
</template>

<script>
import {ref} from 'vue';
import {IconFont} from '@nutui/icons-vue'
import {BankNoReg, IdNumReg, Phone1Reg} from "../../../utils/regUtils";

import useTheme from "../../../hooks/useTheme";
import Taro from "@tarojs/taro";
import {getDictList} from "../../../utils/dictUtils";
import {twPublishAdd, twPublishAudit, twPublishDetailApi, twPublishEdit} from "../../../api/publish";
import {cloneDeep} from "lodash";
import getBaseUrl from "../../../network/baseUrl";
import {Api} from "../../../api/dev";
import {emptyUrl} from "../../../utils/imgUtils";
import {getFileName} from "../../../utils/strUtils";

const {theme, themeVars} = useTheme()
const token = Taro.getStorageSync('token')
const baseUrl = getBaseUrl()
const returnUrl = Api.fileUploadDynamicReturnUrl

const dictList = getDictList("PUBLISH_TYPE")
console.log("PUBLISH_TYPE", dictList)

const formData = ref({
  name: '',
  contactPhone: '',
  contactAddr: '',
  publishType: '',
  contactName: '',
  detailDesc: '',
  imgDesc: [],
})

const formRef = ref(null)

const formRules = {
  contactAddr: [{required: true, message: '请选择联系地址'},],
  publishType: [{required: true, message: '请选择发布类型'},],
  name: [{required: true, message: '请输入商品名称'},],
  contactName: [{required: true, message: '请输入联系人'},],
  contactPhone: [
    {required: true, message: '请填写联系电话'},
    {
      validator: (val) => {
        return new Promise((resolve, reject) => {
          if (!Phone1Reg.test(val)) {
            reject('联系电话格式不正确')
          } else {
            resolve('')
          }
        })
      }
    }
  ],


}

const selectLocation = () => {
  console.log('selectLocation')

//获取位置
  Taro.getLocation({
    type: 'gcj02',
    altitude: true,
    isHighAccuracy: true,
    success: function (res) {
      Taro.chooseLocation({
        latitude: +res.latitude,
        longitude: +res.longitude,
        success(res) {
          console.log("chooseLocation", res)
          const {
            address,
            errMsg,
            latitude,
            longitude,
            name
          } = res
          // 根据经纬度获取省市区
          formData.value.contactAddr = address
          formData.value.contactLngLat = `${longitude},${latitude}`
        }
      })
    },
    fail: function (rr) {
      console.error("getLocation fail", rr)
      Taro.getSetting({
        success: res => {
          if (typeof (res.authSetting['scope.userLocation']) != 'undefined' && !res.authSetting['scope.userLocation']) {
            // 用户拒绝了授权
            Taro.showModal({
              title: '提示',
              content: '您拒绝了定位权限，将无法选择地址，修改位置消息',
              success: res => {
                console.log("showModal ", res)
                if (res.confirm) {
                  // 跳转设置页面
                  Taro.openSetting({
                    success: res => {
                      if (res.authSetting['scope.userLocation']) {
                        // 授权成功，重新定位
                        Taro.getLocation({
                          success: res => {

                            console.log("位置信息 ", res)
                          }
                        });
                      } else {
                        // 没有允许定位权限
                        Taro.showToast({
                          title: '您拒绝了定位权限，将无法选择地址，修改位置消息',
                          icon: 'none'
                        });
                      }
                    }
                  });
                }
              }
            });
          }
        }
      })
    }
  })
}


const submit = () => {
  formRef.value?.validate().then(({valid, errors}) => {
    if (valid) {
      console.log('success:', formData.value)
      const data = cloneDeep(formData.value)
      if (data.imgDesc.length > 0) {
        data.imgDesc = data.imgDesc.map(e => e.url).join(",")
      } else {
        data.imgDesc = ""
      }
      console.log("data", data)
      if (data.id) {
        twPublishEdit(data).then(res => {
          if (res.code == 200) {
            // Taro.showToast({title: res.msg, icon: 'success', duration: 1500,});
            // Taro.navigateBack()
            auditHandle(res.data.id)
          }
        })
      } else {
        twPublishAdd(data).then(res => {
          if (res.code == 200) {
            // Taro.showToast({title: res.msg, icon: 'success', duration: 1500,});
            // Taro.navigateBack()
            auditHandle(res.data.id)

          }
        })
      }

    } else {
      console.warn('error:', errors)
    }
  })
}

const getTwPublishDetail = (id) => {
  twPublishDetailApi(id).then(res => {
    if (200 == res.code) {
      console.log("getTwPublishDetail", res.data)
    }
  }).finally(()=>{
    Taro.hideLoading();
  })
}

const auditHandle = (id) => {
  console.log("确认提交审核", id)
  Taro.showLoading({
    title: '审核中',
  })
  twPublishAudit({id: id}).then(res => {
    console.log("替身结果", res)
    if (200 == res.code) {
      Taro.navigateBack()
      Taro.showToast({title:  res.msg, icon: 'none', duration: 1500,});
    }
  }).finally(()=>{
    Taro.hideLoading()
  })


}
export default {
  methods: {
    emptyUrl() {
      return emptyUrl
    }
  },
  components: {IconFont},

  // 可以使用所有的 Vue 生命周期方法
  mounted() {
  },

  onLoad(options) {
    console.log("options", options.id, formData.value)
    if (options.id) {
      twPublishDetailApi(options.id).then(res => {
        if (200 == res.code) {
          console.log("getTwPublishDetail", res.data)
          formData.value = res.data;
          if (res.data.imgDesc) {
            formData.value.imgDesc = res.data.imgDesc.split(',').map(url => {
              const img = {
                name: getFileName(url),
                url: url,
                status: 'success',
                message: '上传成功',
                type: 'image'
              }
              return img;
            })
          } else {
            formData.value.imgDesc = []
          }

        }
      }).finally(()=>{
        Taro.hideLoading();
      })
    } else {
      formData.value = {
        id: '',
        name: '',
        contactPhone: '',
        contactAddr: '',
        publishType: '',
        contactName: '',
        detailDesc: '',
        imgDesc: [],
      }
    }

  },

  onReady() {
  },

  onShow() {
  },

  onHide() {
  },

  onPullDownRefresh() {
    console.log("onPullDownRefresh")
  },
  onReachBottom() {
    console.log("onReachBottom")
  },


  setup() {


    return {
      theme,
      themeVars,
      Taro,
      token,
      baseUrl,
      returnUrl,
      dictList,

      formData,
      formRef,
      formRules,
      selectLocation,
      submit,


    }
  }

}


</script>

<style>


</style>